// 科室评分具体打分
import { FC, useEffect, useState } from 'react'
import { Breadcrumb, Radio, Button, message, Image, Input, Tooltip } from 'antd'
import {
  connect,
  Dispatch,
  Loading,
  EvaluationStateType,
  Location,
  history,
  PointDetailType
} from 'umi'
import type { RadioChangeEvent } from 'antd'
import produce from 'immer'
import { DownOutlined } from '@ant-design/icons'
import { getStorage } from '@/utils'
import FilePreview from '@/components/FilePreview'
import PreviewPdf from '@/components/preview-pdf'
import styles from './index.less'

interface IProps {
  evaluationModel: EvaluationStateType
  dispatch: Dispatch
  location: Location
}
const CheckMaterials: FC<IProps> = ({
  dispatch,
  location,
  evaluationModel
}) => {
  const { pointDetail, scoreRules, resourceList } = evaluationModel
  const [modalShow, setModalShow] = useState<boolean>(false)
  const [filePath, setFilePath] = useState<string>('')
  const [fileType, setFileType] = useState<string>('')
  const [dataSource, setDataSource] = useState<PointDetailType[]>([])

  const { batchCode, type, questionCode, page } = location.query as {
    batchCode: string
    type: string
    questionCode: string
    page: string
  }

  const [breadcrumb, setBreadcrumb] = useState<string[]>([])
  // 获取评审资源
  const getResourceInfo = (): void => {
    dispatch({
      type: 'evaluationModel/function_getSchoolResourceInfo',
      payload: {
        batchCode,
        unitCode: getStorage('schoolCode'),
        questionCode
      }
    })
  }

  const handlePoint = (e: RadioChangeEvent, code: string) => {
    setDataSource(
      produce((draft) => {
        draft.map((item: PointDetailType) => {
          if (item.code === code) {
            item.ruleCode = e.target.value
          }
        })
      })
    )
  }

  const inputPoint = (
    e: React.ChangeEvent<HTMLInputElement>,
    code: string,
    score: string
  ) => {
    let result = e.target.value.replace(/[^\d{1,}\.\d{1,}|\d{1,}]/g, '')
    // +可以将字符串转变成数字
    if (+result > +score) {
      message.warning(`该项打分不能超过${score}分`)
      return
    }
    setDataSource(
      produce((draft) => {
        draft.map((item: PointDetailType) => {
          if (item.code === code) {
            item.ruleCode = result
          }
        })
      })
    )
  }

  const saveScore = (): void => {
    let temp = dataSource
      .map((item) => ({
        questionCode: item.code,
        ruleCode: item.ruleCode
      }))
      .filter((item) => item.ruleCode)
    if (temp.length != pointDetail.length) {
      message.warning('请确保打完所有打分点')
      return
    }
    // 总分这一项，总分不能超过20分
    if (getStorage('ruleCode') === '60') {
      let value = temp.map((item) => Number(item.ruleCode))
      let sum = value.reduce((prev, current) => prev + current, 0)
      let maxPoint = +getStorage('maxPoint')!
      if (sum > maxPoint) {
        message.warning(`总分不能超过${maxPoint}分`)
        return
      }
    }

    dispatch({
      type: 'evaluationModel/function_saveScore',
      payload: {
        batchCode,
        json: JSON.stringify(temp),
        type,
        id: undefined,
        unitCode: getStorage('schoolCode')
      },
      callback: (response) => {
        if (response.code == 200) {
          message.success('保存成功')
          cancelPoint()
        }
      }
    })
  }

  // 获取打分规则
  const getScoringRules = () => {
    dispatch({
      type: 'evaluationModel/function_getScoringRules',
      payload: {
        ruleCode: '50'
      }
    })
  }

  const setCurrentPreview = (filePath: string) => {
    let type = filePath.substring(filePath.lastIndexOf('.') + 1)
    if (
      [
        'ppt',
        'pptx',
        'xlsx',
        'docx',
        'xls',
        'doc',
        'zip',
        'rar',
        '7z'
      ].includes(type)
    ) {
      window.open(filePath)
      return
    }
    setFileType(type)
    setFilePath(filePath)
  }

  const cancelPoint = () => {
    history.replace({
      pathname: '/assignment/mark',
      query: {
        batchCode,
        type: getStorage('type'),
        questionCode,
        page
      }
    })
  }

  useEffect(() => {
    getResourceInfo()
    setBreadcrumb(JSON.parse(getStorage('breadcrumb')!))
    dispatch({
      type: 'evaluationModel/function_getPointInfoByParentCode',
      payload: {
        batchCode: batchCode,
        parentCode: questionCode,
        type
      }
    })
    getScoringRules()
  }, [])

  // 默认选中第一个非office和压缩文件材料
  useEffect(() => {
    let type = ''
    let path = ''
    try {
      resourceList.files?.forEach((item) => {
        if (item.children) {
          item.children.forEach((v: any) => {
            if (
              ![
                'ppt',
                'pptx',
                'xlsx',
                'docx',
                'xls',
                'doc',
                'zip',
                'rar',
                '7z'
              ].includes(v.url.substring(v.url.lastIndexOf('.') + 1))
            ) {
              path = v.url
              type = v.url.substring(v.url.lastIndexOf('.') + 1)
              throw '找到了'
            }
          })
        }
      })
    } catch (err) {
    } finally {
      if (path) {
        setFilePath(path)
        setFileType(type)
      }
    }
    return () => {
      setFilePath('')
      setFileType('')
    }
  }, [resourceList])

  useEffect(() => {
    pointDetail.forEach((item) => {
      JSON.parse(getStorage('score')!).forEach((v: any) => {
        if (item.code == Object.keys(v)[0] && !item.ruleCode) {
          item.ruleCode = v[item.code]
        }
      })
    })
    setDataSource(pointDetail)
  }, [pointDetail])

  return (
    <>
      <div className={styles['outer-wrapper']}>
        <div className={styles['main-content']}>
          <div className={styles['left-pannel']}>
            <div className={styles['module-title']}>佐证材料列表</div>
            <div className={styles['module-content']}>
              {resourceList?.files?.map((item) => (
                <div key={item.type} className={styles['type-item']}>
                  <div className={styles['material-type']}>
                    <span>{item.type}</span>
                    <DownOutlined />
                  </div>
                  <ul className={styles['material-wrapper']}>
                    {item.children?.map((v: any) => (
                      <li
                        key={v.fileName}
                        className={
                          filePath === v.url
                            ? [
                                `${styles['material-item']}`,
                                `${styles['active-material']}`
                              ].join(' ')
                            : styles['material-item']
                        }
                        onClick={() => setCurrentPreview(v.url)}
                      >
                        {v.fileName}
                      </li>
                    ))}
                  </ul>
                </div>
              ))}
            </div>
          </div>
          <div className={styles['right-pannel']}>
            <div className={styles['material-preview']}>
              <div className={styles['module-title']}>
                <span>佐证材料预览</span>
                {fileType == 'pdf' && (
                  <span
                    onClick={() => {
                      setModalShow(true)
                    }}
                  >
                    点击此处弹窗预览pdf
                  </span>
                )}
              </div>
              <div className={styles['module-content']}>
                <div className={styles['preview-wrapper']}>
                  {['jpg', 'png', 'jpeg', 'gif', 'webp'].includes(fileType) ? (
                    <Image src={`${filePath}`} />
                  ) : ['mp4', 'webm', 'ogg'].includes(fileType) ? (
                    <video
                      src={`${filePath}`}
                      controls
                      width="100%"
                      height="100%"
                    >
                      您的浏览器不支持 video 标签。
                    </video>
                  ) : ['pdf'].includes(fileType) ? (
                    <iframe src={filePath} width="100%" height="100%" />
                  ) : ['mp3', 'wav'].includes(fileType) ? (
                    <audio src={filePath} controls muted loop />
                  ) : (
                    <FilePreview fileType={fileType} filePath={filePath} />
                  )}
                </div>
              </div>

              {/* 弹窗预览pdf */}
              <PreviewPdf
                visible={modalShow}
                filePath={filePath}
                hide={() => {
                  setModalShow(false)
                }}
              />
            </div>
            <div className={styles['mark-pannel']}>
              <div className={styles['module-title']}>
                <div className={styles.breadcrumb}>
                  <Breadcrumb separator=">">
                    {breadcrumb?.map((item) => (
                      <Breadcrumb.Item key={item}>{item}</Breadcrumb.Item>
                    ))}
                  </Breadcrumb>
                </div>

                <div className={styles.rules}>
                  {getStorage('ruleCode') !== '60' ? (
                    <span>
                      评分规则：符合（满分）、基本符合（半分）、不符合（0分）
                    </span>
                  ) : (
                    <span>总分不能超过{getStorage('maxPoint')}分</span>
                  )}
                </div>
              </div>
              <div className={styles['module-content']}>
                <ul>
                  {dataSource?.map((item) => (
                    <li key={item.code} className={styles['detail-item']}>
                      <Tooltip placement="top" title={item.name}>
                        <span className={styles['detail-name']}>
                          {item.name}
                        </span>
                      </Tooltip>

                      {getStorage('ruleCode') !== '60' ? (
                        <Radio.Group
                          onChange={(e) => handlePoint(e, item.code)}
                          value={item.ruleCode}
                        >
                          {scoreRules.map((item) => (
                            <Radio value={item.code} key={item.code}>
                              {item.name}
                            </Radio>
                          ))}
                        </Radio.Group>
                      ) : (
                        <Input
                          value={item.ruleCode}
                          onChange={(e) => inputPoint(e, item.code, item.point)}
                        />
                      )}
                    </li>
                  ))}
                </ul>

                <div className={styles['btn-wrapper']}>
                  <Button onClick={() => cancelPoint()}>取消</Button>
                  <Button type="primary" onClick={() => saveScore()}>
                    提交
                  </Button>
                </div>
              </div>
            </div>
          </div>
        </div>
        <p className={styles['copy-right']}>
          Copyright@ 2016 成都乐培生科技有限公司 蜀ICP备15018125号
        </p>
      </div>
    </>
  )
}

const mapStateToProps = ({
  evaluationModel,
  loading
}: {
  evaluationModel: EvaluationStateType
  loading: Loading
}) => {
  return {
    evaluationModel,
    evaluationLoding: loading.models.evaluationModel
  }
}

export default connect(mapStateToProps)(CheckMaterials)
